﻿using Abp.Application.Services.Dto;
using Abp.AspNetCore.Mvc.Controllers;
using Abp.Web.Models;
using Batman.Cms.Controllers.Inputs;
using Batman.Cms.Core.Core.Attributes;
using Batman.Cms.Core.Tools;
using Batman.Cms.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Cms.Controllers
{
    public class ArticleController : AbpController
    {
        public ArticleAppSvc ArticleAppSvc { get; set; }

        public ToolBox ToolBox { get; set; }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()
        {
            return View(new CreateArticleInput());
        }

        [HttpPost]
        public ActionResult Create(CreateArticleInput model)
        {
            if (!ModelState.IsValid) return View(model);

            ArticleAppSvc.Create(model);

            return Content("新建文章成功");
        }

        [HttpPost]
        public ActionResult GetArticles(PagedResultRequestDto page)
        {
            var result = ArticleAppSvc.GetArticles(page);

            return Json(result);
        }

        [AcceessOriginal]
        [DontWrapResult]
        public async Task<ActionResult> UploadPicture(bool tinymce = false)
        {
            if (Request.Form.Files.Count == 0)
            {
                var result = new AjaxResponse(false) { Error = new ErrorInfo("请上传文件") };
                return Json(result);
            }

            var file = Request.Form.Files[0];

            var stream = file.OpenReadStream();
            var buffer = new byte[stream.Length];
            stream.BeginRead(buffer, 0, (int)stream.Length, null, null);
            var uploadResult = await ToolBox.UpYunTool.UploadSync(buffer);

            if (tinymce) return Json(new { location = uploadResult.Url });
            return Json(uploadResult);
        }

        public ActionResult Update(int id)
        {
            var model = ArticleAppSvc.Get<UpdateArticleInput>(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult Update(UpdateArticleInput model)
        {
            ArticleAppSvc.Update(model);
            return Content("编辑成功");
        }
    }
}
